﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace CallCenter.Security
{
    public class AuthorizeCoreAttribute : AuthorizeAttribute
    {
        public bool IsAuthorized { get; set; }
        protected bool AuthorizeCore(HttpContextBase httpContext)
        {
            this.IsAuthorized = true;
            if (!httpContext.Request.IsAuthenticated)
            {
                this.IsAuthorized = false;
            }
            if (HttpContext.Current.Session["role"] == null)
            {
                this.IsAuthorized = false;
            }
            
            return this.IsAuthorized;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.HttpContext.Response.Redirect("/Account/Login");
                //Here login page is called
                base.HandleUnauthorizedRequest(filterContext);
            }
            else
            {
                if (!this.IsAuthorized)
                {
                    var tempData = new TempDataDictionary();
                    tempData.Add("ErrorReason", "Unauthorized");
                    filterContext.Result = new ViewResult() { ViewName = "Error",  TempData = tempData };
                }
            }
        }
    }
}
